<template>
	<div>

		<label for="text"></label>
		<input id="text" type="text" v-model="message" />
		<button @click="sendMessage">发送消息</button>
		<button @click="closeWebSocket">关闭连接</button>
		<div>{{ websocketMessage }}</div>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				websocket: null,
				message: '',
				websocketMessage: ''
			}
		},

		mounted() {
			if ('WebSocket' in window) {
				this.websocket = new WebSocket("ws://localhost:9090/websocket/123456");

				this.websocket.onerror = () => {
					this.showMessage("打开连接失败");
				};

				this.websocket.onopen = () => {
					this.showMessage("打开连接成功");
				}

				this.websocket.onmessage = (event) => {
					this.showMessage(event.data);
				}

				this.websocket.onclose = () => {
					this.showMessage("关闭连接成功");
				}

				window.onbeforeunload = () => {
					this.websocket.close();
				}
			} else {
				alert('Not support websocket');
			}
		},

		methods: {
			showMessage(message) {
				this.websocketMessage += message + '\n';
			},

			closeWebSocket() {
				this.websocket.close();
			},

			sendMessage() {
				this.websocket.send(this.message);
			}
		}
	}
</script>
